/**
 * 适配 table数据源
 * load: 需要配置singleQueryField
 * 
 * @author xiufu.wang
 */
import { objectProperty, isArray, isObject } from '../../util';
export default function applyAdapt(dataSource) {
    dataSource.tableAsyncTreeload = function (row, treeNode, cb) {
        const opt = dataSource.mergeOption
        const keyFiled = row.rowKey
        const queryFiled = opt.singleQueryField || 'query'
        const res = dataSource.selectQueryLoad({ [queryFiled]: row[keyFiled] }, true)
        if (res.then) {
            res.then((data) => {
                cb(dataSource.handleFormatDatas(data, opt) || [])
            })
        } else {
            cb(dataSource.handleFormatDatas(res, opt) || [])
        }
    }

    /**
     * 获取服务端返回的表格统计数据，结构是一个对象 {...column, sumText: '某某统计'}
     */
    dataSource.getSummaryData = function () {
        //原始数据
        const orgData = dataSource.getPrimitiveData()
        const opt = dataSource.mergeOption
        const summaryDataField = opt.summaryDataField
        if (!summaryDataField) {
            return null
        }
        return objectProperty(orgData || {}, summaryDataField, {})
    }

    // 数据行分组显示
    dataSource.getSpanMethod = function () {
        const opt = dataSource.mergeOption
        const groupField = opt.groupField
        if (!groupField || (isArray(groupField) && groupField.length === 0)) {
            return
        }
        // 如果数据源配置 groupField,这里提供一个默认的SpanMethod逻辑处理
        return function ({row, column}) {
            const prop = column.property
            const _rowSpans_ = row._rowSpans_
            let rowspan = 1
            if (_rowSpans_ && (prop in _rowSpans_)) { 
                rowspan =  _rowSpans_[prop]
            }
            return {
                colspan: 1,
                rowspan: rowspan
            }
        }
    }
}